/*
 * Copyright (c)$today.year.month.day
 *  admin:郑程荣.
 *  文件名:HistoryTimeDataActivity.java
 *  项目功能:
 */

/*
 * Copyright (c)$today.year.month.day
 *  admin:郑程荣.
 *  文件名:ActualTimeDataActivity.java
 *  项目功能:
 */

package com.jg.myproject.module.historydata;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.github.mikephil.charting.charts.LineChart;
import com.jg.myproject.adapter.ExamplePagerAdapter;
import com.jg.myproject.api.Const;
import com.jg.myproject.api.bean.BaseEntity;
import com.jg.myproject.api.bean.CommonRequestBean;
import com.jg.myproject.api.bean.reponse.CommonReponseBean;
import com.jg.myproject.module.base.BaseActivity;
import com.jg.myproject.presenter.ActualTimePresenter;
import com.jg.myproject.presenter.HistoryTimePresenter;
import com.jg.myproject.pview.IActualTimeView;
import com.jg.myproject.utils.LineUtils;
import com.jg.myproject.utils.RxSPTool;
import com.jg.myproject.widget.CustomScrollViewPager;
import com.jg.myproject.widget.TableDividerItemDecoration;
import com.zcr.myproject.R;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;

/**
 * Created by llz on 2018/11/16.
 */
public class HistoryTimeDataActivity extends BaseActivity   implements IActualTimeView, View.OnClickListener {
    private static final String[] CHANNELS = new String[]{"曲线图", "监测数据", "监测状态"};
    @BindView(R.id.magic_indicator)
    MagicIndicator mMagicIndicator;
    @BindView(R.id.view_pager)
    CustomScrollViewPager mViewPager;
    List<String> mDataList = Arrays.asList(CHANNELS);
    ExamplePagerAdapter mExamplePagerAdapter ;
    List<View> views = new ArrayList<View>();
    LineChart chart1;
    View view01;
    RadioGroup view01_rg_check;
    String sensorName01="V";
    View view02;
    SwipeRefreshLayout view02_swipelayout;
    RecyclerView view02_rv_content;
    private BaseQuickAdapter mBaseQuickAdapter;
    public int mNextRequestPage = 1;
    RadioGroup view02_rg_check;
    String sensorName02="V";
    ArrayList<String> pointList = new ArrayList<String>();
    LinearLayout ll_choic_point;
    TextView tv_point_text,tv_search_text;

    View view03;
    SwipeRefreshLayout view03_swipelayout;
    RecyclerView view03_rv_content;
    private BaseQuickAdapter mBaseQuickAdapter2;
    public int mNextRequestPage2 = 1;
    RadioGroup view03_rg_check;
    String sensorName03="V";
    View view03FooterView;
    private TextView view03_tv_01,view03_tv_02;


    HistoryTimePresenter mPresenter;

    public boolean mIsRefresh;

    public boolean mIsRefresh2;

    private ArrayList<CommonReponseBean.CommonReponseChildBean> mBeans;
    private ArrayList<CommonReponseBean.CommonReponseChildBean> mBeans2;

    private View notDataView2;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_history_time_data;
    }
    @Override
    protected void initViews() {
        initTitle(true,"历史数据");
        mPresenter = new HistoryTimePresenter(this);
        mViewPager = (CustomScrollViewPager) findViewById(R.id.view_pager);
        view01 = View.inflate(this,R.layout.activity_actual_time_data_view01,null);
        chart1 = view01.findViewById(R.id.chart1);
        chart1.getDescription().setEnabled(false);
        chart1.setDrawGridBackground(false);
        chart1.animateX(750);
        chart1.setNoDataText("");
        view01_rg_check = view01.findViewById(R.id.rg_check);
        initChart1();
        view02 = View.inflate(this,R.layout.activity_actual_time_data_view02,null);
        view02_swipelayout = view02.findViewById(R.id.swipeLayout);
        view02_rv_content = view02.findViewById(R.id.rv_content);
        view02_rg_check = view02.findViewById(R.id.rg_check);
        ll_choic_point = view02.findViewById(R.id.ll_choic_point);
        ll_choic_point.setOnClickListener(this);
        tv_point_text =view02.findViewById(R.id.tv_point_text);
        tv_search_text = view02.findViewById(R.id.tv_search_text);
        tv_search_text.setOnClickListener(this);
        initChart2();
        view03 = View.inflate(this,R.layout.activity_actual_time_data_view03,null);
        view03_tv_01 = view03.findViewById(R.id.view03_tv_01);
        view03_tv_02 = view03.findViewById(R.id.view03_tv_02);
        view03_swipelayout = view03.findViewById(R.id.swipeLayout);
        view03_rv_content = view03.findViewById(R.id.rv_content);
        view03_rg_check = view03.findViewById(R.id.rg_check);
        initChart3();
        views.add(view01);
        views.add(view02);
        views.add(view03);
        mExamplePagerAdapter = new ExamplePagerAdapter(mDataList,views);
        mViewPager.setAdapter(mExamplePagerAdapter);
        initMagicIndicator2();
    }




    @Override
    protected void updateViews(final boolean isRefresh) {
        getData();
        // 更新实时数据
        mIsRefresh=true;
        getdata02();
        view01_rg_check.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId){
                    case R.id.rb_check01:
                        sensorName01 = "V";
                        break;
                    case R.id.rb_check02:
                        sensorName01 = "F";
                        break;
                    case R.id.rb_check03:
                        sensorName01 = "H";
                        break;
                    case R.id.rb_check04:
                        sensorName01 = "L";
                        break;
                }
                getData();
            }
        });

        view02_rg_check.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId){
                    case R.id.rb_check01:
                        sensorName02 = "V";
                        break;
                    case R.id.rb_check02:
                        sensorName02 = "F";
                        break;
                    case R.id.rb_check03:
                        sensorName02 = "H";
                        break;
                    case R.id.rb_check04:
                        sensorName02 = "L";
                        break;
                }
                mIsRefresh=true;
                mNextRequestPage=1;
                showLoading();
                getdata02();
            }
        });
        view03_rg_check.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId){
                    case R.id.rb_check01:
                        sensorName03 = "V";
                        break;
                    case R.id.rb_check02:
                        sensorName03 = "F";
                        break;
                    case R.id.rb_check03:
                        sensorName03 = "H";
                        break;
                    case R.id.rb_check04:
                        sensorName03 = "L";
                        break;
                }
                mIsRefresh2=true;
                mNextRequestPage2=1;
                showLoading();
                getdata03();
            }

        });
    }


    private void initChart1() {
      /*  xAxisValue.add("123"); //横坐标数据
        xAxisValue.add("123");
        xAxisValue.add("123");
        yAxisValue.add(12.0f);//第一根折线数据
        yAxisValue.add(11.0f);
        yAxisValue.add(1.0f);
        yAxisValue2.add(5.0f);//第二根折线数据
        yAxisValue2.add(4.0f);
        yAxisValue2.add(3.0f);
        titles.add("当前值");// 每根折线数据的标题
        titles.add("预警值");
        entriesList.add(yAxisValue);
        entriesList.add(yAxisValue2);
        LineUtils.setLineChart(chart1,titles,entriesList,xAxisValue,false);*/
    }

    private void initChart2() {
        view02_rv_content.setLayoutManager(new LinearLayoutManager(this));
        view02_rv_content.addItemDecoration(new TableDividerItemDecoration(this));
        notDataView2 = getLayoutInflater().inflate(R.layout.empty_view, (ViewGroup) view02_rv_content.getParent(), false);
        mBeans = new ArrayList<CommonReponseBean.CommonReponseChildBean>();
        mBaseQuickAdapter = new BaseQuickAdapter<CommonReponseBean.CommonReponseChildBean, BaseViewHolder>(R.layout.item_actual_item_data2, mBeans) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, CommonReponseBean.CommonReponseChildBean bean) {
                TextView tv_01 = baseViewHolder.getView(R.id.tv_01);
                TextView tv_02 = baseViewHolder.getView(R.id.tv_02);
                TextView tv_03 = baseViewHolder.getView(R.id.tv_03);
                TextView tv_04 = baseViewHolder.getView(R.id.tv_04);
                tv_01.setText(bean.getSensorCode());
                tv_02.setText(bean.getAcsValue());
                tv_03.setText(bean.getAlarmState());
                if(bean.getAlarmState().equals("正常")){
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_image_green);
                    drawable.setBounds(2, 0, 32, 32);
                    tv_03.setCompoundDrawables(drawable,null,null,null);
                }else  if(bean.getAlarmState().equals("预警")){
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_image_yellow);
                    drawable.setBounds(2, 0, 32, 32);
                    tv_03.setCompoundDrawables(drawable,null,null,null);
                }else{
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_image_red);
                    drawable.setBounds(2, 0, 32, 32);
                    tv_03.setCompoundDrawables(drawable,null,null,null);
                }
                tv_04.setText(bean.getInsertDateStr());
            }
        };
        mBaseQuickAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mIsRefresh = mNextRequestPage == 1;
                getdata02();
            }
        }, view02_rv_content);
        initRefreshLayout(); // 下拉刷新
        view02_rv_content.setAdapter(mBaseQuickAdapter);
    }


    private void initChart3() {
        view03_rv_content.setLayoutManager(new LinearLayoutManager(this));
        view03_rv_content.addItemDecoration(new TableDividerItemDecoration(this));
        mBeans2 = new ArrayList<CommonReponseBean.CommonReponseChildBean>();
        mBaseQuickAdapter2 = new BaseQuickAdapter<CommonReponseBean.CommonReponseChildBean, BaseViewHolder>(R.layout.item_actual_item_data3, mBeans2) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, CommonReponseBean.CommonReponseChildBean bean) {
                TextView tv_01 = baseViewHolder.getView(R.id.tv_01);
                TextView tv_02 = baseViewHolder.getView(R.id.tv_02);
                TextView tv_03 = baseViewHolder.getView(R.id.tv_03);
                TextView tv_04 = baseViewHolder.getView(R.id.tv_04);
                tv_01.setText(baseViewHolder.getAdapterPosition()+1+"");
                tv_02.setText(bean.getDeviceCode());
                tv_03.setText(bean.getMonitorSectionDate());
                if(bean.getSectionState().equals("0")){
                    tv_04.setText("正常");
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_image_green);
                    drawable.setBounds(2, 0, 32, 32);
                    tv_04.setCompoundDrawables(drawable,null,null,null);
                }else  if(bean.getSectionState().equals("1")){
                    tv_04.setText("预警");
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_image_yellow);
                    drawable.setBounds(2, 0, 32, 32);
                    tv_04.setCompoundDrawables(drawable,null,null,null);
                }else if(bean.getSectionState().equals("2")){
                    tv_04.setText("报警");
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_image_red);
                    drawable.setBounds(2, 0, 32, 32);
                    tv_04.setCompoundDrawables(drawable,null,null,null);
                }else if(bean.getSectionState().equals("3")){
                    tv_04.setText("暂停");
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_image_red);
                    drawable.setBounds(2, 0, 32, 32);
                    tv_04.setCompoundDrawables(drawable,null,null,null);
                }else if(bean.getSectionState().equals("4")){
                    tv_04.setText("结束");
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_image_green);
                    drawable.setBounds(2, 0, 32, 32);
                    tv_04.setCompoundDrawables(drawable,null,null,null);
                }
            }
        };
        mBaseQuickAdapter2.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mIsRefresh2 = mNextRequestPage2 == 1;
                getdata03();
            }
        }, view03_rv_content);
        initRefreshLayout2(); // 下拉刷新
        view03FooterView = getLayoutInflater().inflate(R.layout.activity_actual_time_data_view03_bottom, (ViewGroup) view03_rv_content.getParent(), false);
       // mBaseQuickAdapter2.addFooterView(view03FooterView);
        view03_rv_content.setAdapter(mBaseQuickAdapter2);
    }

    private void getData() {
        showLoading();
        CommonRequestBean commonRequestBean = new CommonRequestBean();
        String monitorPartCode = RxSPTool.getString(HistoryTimeDataActivity.this,Const.MONITORPARTCODE);
        String userId = RxSPTool.getString(HistoryTimeDataActivity.this,Const.USERID);
        commonRequestBean.setMonitorPartCode(monitorPartCode);
        commonRequestBean.setSensorName(sensorName01);
        commonRequestBean.setUserId(userId);
        mPresenter.getData(commonRequestBean);//获取实时数据
    }

    private void getdata02() {
        CommonRequestBean commonRequestBean = new CommonRequestBean();
        String monitorPartCode = RxSPTool.getString(HistoryTimeDataActivity.this,Const.MONITORPARTCODE);
        String userId = RxSPTool.getString(HistoryTimeDataActivity.this,Const.USERID);
        commonRequestBean.setMonitorPartCode(monitorPartCode);
        commonRequestBean.setSensorName(sensorName02);
        commonRequestBean.setUserId(userId);
        commonRequestBean.setPageNo(mNextRequestPage);
        commonRequestBean.setPageSize(Const.PAGE_SIZE);
        commonRequestBean.setSensorCode(tv_point_text.getText().toString());
        mPresenter.getData2(commonRequestBean);//获取实时数据
    }

    private void getdata03() {
        CommonRequestBean commonRequestBean = new CommonRequestBean();
        String monitorPartCode = RxSPTool.getString(HistoryTimeDataActivity.this,Const.MONITORPARTCODE);
        String userId = RxSPTool.getString(HistoryTimeDataActivity.this,Const.USERID);
        commonRequestBean.setMonitorPartCode(monitorPartCode);
        commonRequestBean.setSensorName(sensorName03);
        commonRequestBean.setUserId(userId);
        commonRequestBean.setPageNo(mNextRequestPage2);
        commonRequestBean.setPageSize(Const.PAGE_SIZE);
        mPresenter.getData3(commonRequestBean);//获取实时数据
    }
    private void initRefreshLayout() {
        view02_swipelayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mNextRequestPage = 1;
                mIsRefresh = true;
                mBaseQuickAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
                getdata02();
            }
        });
    }

    private void initRefreshLayout2() {
        view03_swipelayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mNextRequestPage2 = 1;
                mIsRefresh2 = true;
                mBaseQuickAdapter2.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
                getdata03();
            }
        });
    }

    // 返回实时曲线
    @Override
    public void getReponseBeans(BaseEntity<CommonReponseBean> bean) {
        if(bean.getBeans()!=null&bean.getBeans().size()>0){
            chart1.clear();

            int max=0;
            for(int i=0;i<bean.getBeans().size();i++){
                int  n = bean.getBeans().get(i).getValueList().size();
                if(n>max){
                    max = n ;
                }
            }
            Matrix matrix = new Matrix();
            matrix.postScale(max/4==0?1f:max/4f,1f);
            chart1.getViewPortHandler().refresh(matrix, chart1, false);
            //重设所有缩放和拖动，使图表完全适合它的边界（完全缩小）。
            chart1.fitScreen();
            //缩放第二种方式
            chart1.getViewPortHandler().getMatrixTouch().postScale(max/4==0?1f:max/4f, 1f);
            List<String> xAxisValue = new ArrayList<String>();
            List<String> titles = new ArrayList<>();
            List<List<Float>> entriesList = new ArrayList<>();
            for(int i=0;i<bean.getBeans().size();i++){
                    CommonReponseBean commonReponseBean = bean.getBeans().get(i);
                    String title = commonReponseBean.getName();
                    titles.add(title);
                    List<CommonReponseBean.CommonReponseChildBean> list = commonReponseBean.getValueList();
                    List<Float> yAxisValue = new ArrayList<Float>();
                    for(CommonReponseBean.CommonReponseChildBean commonReponseChildBean:list){
                        xAxisValue.add(commonReponseChildBean.getInsertDateStr());
                        yAxisValue.add(Float.valueOf(commonReponseChildBean.getAcsValue()));
                    }
                    entriesList.add(yAxisValue);
                }
            LineUtils.setLineChart(chart1,titles,entriesList,xAxisValue,false);
        }
    }

    //实时数据
    @Override
    public void getReponseBeans2(BaseEntity<CommonReponseBean> bean) {
        if(bean.getBeans()!=null&&bean.getBeans().size()>0) {
            pointList.clear();
            pointList.addAll(bean.getBeans().get(0).getPointList());
        }
        mNextRequestPage++;
        int size = bean.getBeans().get(0).getPointDataList() == null ? 0 : bean.getBeans().get(0).getPointDataList().size();
        if (mIsRefresh) {
            if(size == 0){
                mBaseQuickAdapter.setEmptyView(notDataView2);
                mBeans.clear();
                mBaseQuickAdapter.setNewData(mBeans);
            }else{
                mBeans.clear();
                mBeans.addAll(bean.getBeans().get(0).getPointDataList());
                mBaseQuickAdapter.setNewData(mBeans);
            }
            mBaseQuickAdapter.setEnableLoadMore(true);
            view02_swipelayout.setRefreshing(false);
        } else {
            if (size > 0) {
                mBeans.addAll(bean.getBeans().get(0).getPointDataList());
                mBaseQuickAdapter.addData(mBeans);
            }
           // view02_swipelayout.setRefreshing(true);
        }
        if (size < Const.PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mBaseQuickAdapter.loadMoreEnd(mIsRefresh);
        } else {
            mBaseQuickAdapter.loadMoreComplete();
        }
    }

    //检测状态
    @Override
    public void getReponseBeans3(BaseEntity<CommonReponseBean> bean) {
        view03_tv_01.setText( bean.getBeans().get(0).getMonitorPointInfo().getAlarmPointsForM());
        view03_tv_02.setText( bean.getBeans().get(0).getMonitorPointInfo().getAllPointsForM());
        mNextRequestPage2++;
        int size = bean.getBeans().get(0).getSectionDataList() == null ? 0 : bean.getBeans().get(0).getSectionDataList().size();
        if (mIsRefresh2) {
            if(size == 0){
               // mBaseQuickAdapter2.setEmptyView(notDataView2);
                mBeans2.clear();
                mBaseQuickAdapter2.setNewData(mBeans2);
            }else{
                mBeans2.clear();
                mBeans2.addAll(bean.getBeans().get(0).getSectionDataList());
                mBaseQuickAdapter2.setNewData(mBeans2);
            }
            mBaseQuickAdapter2.setEnableLoadMore(true);
            view03_swipelayout.setRefreshing(false);
        } else {
            if (size > 0) {
                mBeans2.addAll(bean.getBeans().get(0).getSectionDataList());
                mBaseQuickAdapter2.addData(mBeans2);
            }
            // view02_swipelayout.setRefreshing(true);
        }
        if (size < Const.PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mBaseQuickAdapter2.loadMoreEnd(mIsRefresh2);
        } else {
            mBaseQuickAdapter2.loadMoreComplete();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_choic_point:
                new MaterialDialog.Builder(this)
                        .title("选择")
                        .items(pointList)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                tv_point_text.setText(text);
                            }
                        })
                        .show();
                break;
            case R.id.tv_search_text:
                mNextRequestPage = 1;
                mIsRefresh = true;
                getdata02();
                break;
        }
    }




    private void initMagicIndicator2() {
        mMagicIndicator.setBackgroundColor(Color.parseColor("#ffffff"));
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);//设置全屏
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }
            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new SimplePagerTitleView(context);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setNormalColor(Color.parseColor("#000000"));
                simplePagerTitleView.setSelectedColor(HistoryTimeDataActivity.this.getResources().getColor(R.color.common_main_color));
                simplePagerTitleView.setTextSize(12);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(index==2){
                            mNextRequestPage2 = 1;
                            mIsRefresh2 = true;
                            getdata03();
                        }
                        mViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }
            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_MATCH_EDGE);
                indicator.setColors(HistoryTimeDataActivity.this.getResources().getColor(R.color.common_main_color));
                return indicator;
            }
        });
        mMagicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mMagicIndicator, mViewPager);
    }
}
